<?php
namespace ImiDemo\HttpDemo\MainServer\Controller;

use Imi\Controller\HttpController;
use Imi\Server\View\Annotation\View;
use Imi\Server\Route\Annotation\Route;
use Imi\Server\Route\Annotation\Action;
use Imi\Server\Route\Annotation\Controller;
use Imi\Pool\PoolManager;
use Imi\Util\MuiltDefer;

/**
 * Redis操作 演示
 * @Controller("/Redis/")
 * @View(renderType="json")
 */
class Redis extends HttpController
{
    /**
     * Redis操作 演示
     * 访问：http://127.0.0.1:8080/Redis/test
     * 
     * @Action
     * @return void
     */
    public function test()
    {
        $datetime = PoolManager::use('redis', function($resource, \Imi\Redis\Redis $redis){
            $redis->set('imi:redis:test', date('Y-m-d H:i:s'));
            return $redis->get('imi:redis:test');
        });
        return [
            'datetime'    =>    $datetime,
        ];
    }

    /**
    * Redis操作 演示
    * 访问：http://127.0.0.1:8080/Redis/testDefer
    * 
    * @Action
    * @return void
    */
    public function testDefer()
    {
        $time = microtime(true);

        $res1 = PoolManager::getResource('redis');
        $res2 = PoolManager::getResource('redis');

        $db1 = $res1->getInstance();
        $db2 = $res2->getInstance();

        $defer1 = $db1->deferGet('imi:redis:test');
        $defer2 = $db2->deferGet('imi:redis:test');

        return [
            'result1'    =>    $defer1->call(),
            'result2'    =>    $defer2->call(),
            'time'        =>    microtime(true) - $time,
        ];
        return [];
    }

    /**
    * Redis操作 演示
    * 访问：http://127.0.0.1:8080/Redis/testMuiltDefer
    * 
    * @Action
    * @return void
    */
    public function testMuiltDefer()
    {
        $time = microtime(true);

        $res1 = PoolManager::getResource('redis');
        $res2 = PoolManager::getResource('redis');

        $db1 = $res1->getInstance();
        $db2 = $res2->getInstance();

        $defer1 = $db1->deferGet('imi:redis:test');
        $defer2 = $db2->deferGet('imi:redis:test');

        list($result1, $result2) = MuiltDefer::call($defer1, $defer2);

        return [
            'result1'    =>    $result1,
            'result2'    =>    $result2,
            'time'        =>    microtime(true) - $time,
        ];
        return [];
    }


}